package com.itfreer.file.remote.upload;

import com.itfreer.file.FileSegmentInfo;
import com.itfreer.file.remote.FileService;
import com.itfreer.file.remote.FileProgressListener;
import com.itfreer.utils.collection.Queue;

import java.util.List;

/**
 * 定义上传线程，实现文件的片段上传
 */
public class UploadThread extends Thread {

    private String bucketName;
    private String objectKey;
    private FileSegmentInfo segmentInfo;
    // 文件下载队列
    private final Queue<Long> uploadQueue;
    // 线程列表
    private final List<Long> threadList;
    // 进度监听
    private final FileProgressListener listener;

    public UploadThread(
            String bucketName, String objectKey,
            FileSegmentInfo segmentInfo,
            Queue<Long> queue,
            List<Long> threadList,
            FileProgressListener listener){
        this.bucketName = bucketName;
        this.objectKey = objectKey;
        this.segmentInfo = segmentInfo;
        this.uploadQueue = queue;
        this.threadList = threadList;
        this.listener = listener;
    }

    /**
     * 进行文件下载
     */
    @Override
    public void run() {
        Boolean fInfo = FileService.instance.uploadFile(bucketName, objectKey, segmentInfo);
        if(fInfo==null || fInfo == false){
            // 失败，则退回到队列重新下载
            uploadQueue.offer(segmentInfo.getSegmentIndex());
            // 退出线程
            threadList.remove(getId());
        }else{
            // 退出线程
            threadList.remove(getId());
            if(listener!=null){
                listener.onSize(segmentInfo.getSegmentCount(), segmentInfo.getSegmentIndex());
            }
        }
    }

}
